import { Request, Response } from 'express';
import { UserService } from '../services/UserService';

export class UserController {
  private userService: UserService;

  constructor() {
    this.userService = new UserService();
  }

  // 创建用户
  createUser = async (req: Request, res: Response): Promise<void> => {
    try {
      const { username, email, password, firstName, lastName } = req.body;
      
      // 检查用户名和邮箱是否已存在
      const existingUserByUsername = await this.userService.findUserByUsername(username);
      if (existingUserByUsername) {
        res.status(400).json({ error: '用户名已存在' });
        return;
      }

      const existingUserByEmail = await this.userService.findUserByEmail(email);
      if (existingUserByEmail) {
        res.status(400).json({ error: '邮箱已存在' });
        return;
      }

      const user = await this.userService.createUser({
        username,
        email,
        password,
        firstName,
        lastName,
      });

      res.status(201).json({
        message: '用户创建成功',
        user,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '创建用户失败' });
    }
  };

  // 获取用户详情
  getUserById = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const user = await this.userService.findUserById(parseInt(id));
      
      if (!user) {
        res.status(404).json({ error: '用户不存在' });
        return;
      }

      res.json({ user });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '获取用户失败' });
    }
  };

  // 获取用户列表
  getAllUsers = async (req: Request, res: Response): Promise<void> => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      
      const { users, total } = await this.userService.getAllUsers(page, limit);
      
      res.json({
        users,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '获取用户列表失败' });
    }
  };

  // 更新用户
  updateUser = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const updateData = req.body;
      
      // 移除不允许更新的字段
      delete updateData.id;
      delete updateData.createdAt;
      delete updateData.updatedAt;
      
      const user = await this.userService.updateUser(parseInt(id), updateData);
      
      if (!user) {
        res.status(404).json({ error: '用户不存在' });
        return;
      }

      res.json({
        message: '用户更新成功',
        user,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '更新用户失败' });
    }
  };

  // 删除用户
  deleteUser = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const success = await this.userService.deleteUser(parseInt(id));
      
      if (!success) {
        res.status(404).json({ error: '用户不存在' });
        return;
      }

      res.json({ message: '用户删除成功' });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '删除用户失败' });
    }
  };
}